package com.example.forum_system.controller;

import com.example.forum_system.common.AppResult;
import com.example.forum_system.common.ResultCode;
import com.example.forum_system.config.AppConfig;
import com.example.forum_system.exception.ApplicationException;
import com.example.forum_system.model.User;
import com.example.forum_system.services.IUserService;
import com.example.forum_system.utils.MD5Utils;
import com.example.forum_system.utils.StringUtils;
import com.example.forum_system.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author: 啵啵虎
 * @Date: 2024-05-15  22:09
 */

@Slf4j
@Api(tags = "用户接口")
@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //1、判断密码与确认密码是否相同
        if (!password.equals(passwordRepeat)){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2、判断用户是否存在
        User existUser=userService.selectByUsername(username);
        if (existUser!=null){
            //用户已存在
            return AppResult.failed(ResultCode.FAILED_USER_EXISTS);
        }
        //3、生成密码的密文
        //生成盐
        String salt= UUIDUtils.UUID_32();
        //生成密文
        String ciphertext= MD5Utils.md5Salt(password,salt);
        //构造user对象
        User user=new User();
        user.setUsername(username);  //用户名
        user.setNickname(nickname);  //昵称
        user.setPassword(ciphertext);  //密码（密文）
        user.setSalt(salt);  //盐
        //调用service
        userService.createNormalUser(user);
        //返回正常响应
        return  AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult<User> login(HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                                 @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //调用Service
        User user=userService.login(username,password);
        if (user==null){
            //返回错误
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //获取session对象
        HttpSession session= request.getSession(true);  //没有的话创建一个
        //把用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户详情")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户Id") @RequestParam(value = "id",required = false) Long id){
        //定义一个返回的User对象
        User user;
        //校验Id是否为空，根据Id的值来处理不同的逻辑
        if (id==null){
            //从session中获取用户信息
            HttpSession session= request.getSession(false);
            user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        }else {
            //从数据库中查询用户信息
            user=userService.selectById(id);
        }
        //返回用户信息
        return AppResult.success(user);
    }

    @ApiOperation("用户注销")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //1、获取session
        HttpSession session=request.getSession(false);
        //2、注销session
        if (session!=null){
            //销毁session
            session.invalidate();
        }
        //3、返回结果
        return AppResult.success("注销成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        //非空校验
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNum)
                && StringUtils.isEmpty(remark) && gender==null){
            //返回错误描述
            return AppResult.failed("请输入要修改的内容");
        }
        //获取当前登录的用户信息
        HttpSession session= request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //构造更新对象
        User updateUser=new User();
        updateUser.setId(user.getId());  //id
        updateUser.setUsername(username);  //用户名
        updateUser.setNickname(nickname);  //昵称
        updateUser.setGender(gender);  //性别
        updateUser.setPhoneNum(phoneNum);  //电话号
        updateUser.setEmail(email);  //邮箱
        updateUser.setRemark(remark);  //个人简介
        //调用Service
        userService.modifyInfo(updateUser);
        //获取数据库中最新的user信息
        user=userService.selectById(user.getId());
        //更新session中的user对象
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);
        //返回结果
        return AppResult.success(user);
    }

    @ApiOperation("更新密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //1、校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2、获取当前登录的用户信息
        HttpSession session= request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //校验用户是否存在
        if (user==null || user.getDeleteState()==1){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3、调用Service
        userService.modifyPassword(user.getId(), newPassword,oldPassword);
        //4、销毁session
        if (session!=null){
            session.invalidate();
        }
        //5、返回结果
        return AppResult.success();
    }
}
